import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, logout, getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref({})
  const roles = ref([])
  const permissions = ref([])

  // 是否已登录
  const isLoggedIn = computed(() => !!token.value)

  // 用户角色
  const userRoles = computed(() => roles.value)

  // 用户权限
  const userPermissions = computed(() => permissions.value)

  // 登录
  const loginAction = async (loginData) => {
    try {
      const response = await login(loginData)
      token.value = response.token
      localStorage.setItem('token', response.token)
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const response = await getUserInfo()
      userInfo.value = response
      roles.value = response.roles || []
      permissions.value = response.permissions || []
      return response
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('登出失败', error)
    } finally {
      resetState()
    }
  }

  // 重置状态
  const resetState = () => {
    token.value = ''
    userInfo.value = {}
    roles.value = []
    permissions.value = []
    localStorage.removeItem('token')
  }

  // 检查权限
  const hasPermission = (permission) => {
    return permissions.value.includes(permission)
  }

  // 检查角色
  const hasRole = (role) => {
    return roles.value.includes(role)
  }

  return {
    token,
    userInfo,
    roles,
    permissions,
    isLoggedIn,
    userRoles,
    userPermissions,
    loginAction,
    getUserInfoAction,
    logoutAction,
    resetState,
    hasPermission,
    hasRole
  }
})